<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2019/1/18
 * Time: 15:59
 */

namespace app\storage\service;


use app\storage\model\SupplierModel;
use cmf\controller\AdminBaseController;
use service\k3\K3ReaderFactory;

class SupplierService extends AdminBaseController
{

    /**从K3上添加厂商或供应商
     * @param array $supplierId
     * @param bool $write
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public static function create_supplier($supplierId = [],$write = true)
    {
        if (empty($supplierId)) {
            return ret_template(true, "厂商号为空");
        }

        if (is_string($supplierId)) {
            $temp = $supplierId;
            unset($supplierId);
            $supplierId[0] = $temp;
        }

        $supplierModel = new SupplierModel();
        $supplierList = $supplierModel->column('supplier_id');
        $supplierDiff = array_diff($supplierId, $supplierList);
        if (empty($supplierDiff)) {
            $supplierInfo =  $supplierModel->whereIn('supplier_id',$supplierId)->select()->toArray();
            return ret_template(true, '数据库已经存在该厂商',$supplierInfo);
        }
        $supplierInfo = [];
        foreach ($supplierDiff as $item) {
            $subK3 = K3ReaderFactory::read('supplier', $item);
            if (empty($subK3)) {
                return ret_template(false, "K3中不存在厂商({$item})");
            }
            $supplierInfo[] = $subK3[0];
        }
        foreach ($supplierInfo as $k=> $item) {
            $supplierInfo[$k]['uuid'] = create_uuid();
        }
        if ($write) {
            $supplierModel->startTrans();
            $result = $supplierModel->insertAll($supplierInfo);
            if ($result) {
                $supplierModel->commit();
                return ret_template(true, '获取成功', $supplierInfo);
            } else {
                $supplierModel->rollback();
                return ret_template(false, '插入数据库失败');
            }
        } else {
            return ret_template(true, '获取成功', $supplierInfo);
        }
    }



}